<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import {
  getSpuTrademarkAPI,
  getSpuImageAPI,
  getSpuSaleAttrAPI,
  getSpuHasSaleAttrAPI,
  saveSpuAPI,
  addSpuAPI
} from '@api/product/spu/index.ts'
import type {
  spuTrademarkItemType,
  spuResponseDataRecordsType,
  spuImageItemType,
  spuAllSaleItemType,
  spuSaleItemType,
  spuSaleAttrValueListType,
} from '@api/product/spu/type.ts'
import { ElMessage } from 'element-plus'

defineProps({
  screen: {
    type: Boolean,
    required: true,
  },
})

// 获取spu品牌与属性的数据
const spuTrademarkList = ref<spuTrademarkItemType[]>([])
const initFn = () => {
  Promise.all([getSpuTrademarkAPI(), getSpuSaleAttrAPI()]).then((res) => {
    console.log(res)
    spuTrademarkList.value = res[0].data
    spuAttrList.value = res[1].data
  })
}
onMounted(() => initFn())

// 照片墙事件-----------------------
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// 点击取消按钮返回显示表格
const emit = defineEmits(['update:screen', 'getDataFn'])
const handleCancelFn = () => {
  emit('update:screen', false)
  spuData.value = {
    id: '',
    spuName: '',
    category3Id: '',
    tmId: '',
    description: '',
  }
}

/**
 * 获取数据的方法，暴露出去给父组件使用
 * spuData：spu详情数据
 * spuImageList：spu照片墙数据
 * spuAttrList：spu销售属性数组
 *
 */
const spuData = ref<spuResponseDataRecordsType>({
  id: '',
  spuName: '',
  category3Id: '',
  tmId: '',
  description: '',
  spuSaleAttrList: [],
  spuImageList: [],
})
const spuImageList = ref<spuImageItemType[]>([])
const spuAttrList = ref<spuAllSaleItemType[]>([])
const spuHasAttrList = ref<spuSaleItemType[]>([])
const typeIsInfo = ref<boolean>(false)
const initAttrDataFn = (row: spuResponseDataRecordsType, isInfo: boolean =false) => {
  spuData.value = row
  typeIsInfo.value = isInfo

  Promise.all([getSpuImageAPI(row.id), getSpuHasSaleAttrAPI(row.id)]).then(
    (res) => {
      console.log(res)
      spuImageList.value = res[0].data.map((item) => ({
        ...item,
        url: item.imgUrl,
        name: item.imgName,
      }))
      spuHasAttrList.value = res[1].data
    },
  )
}

// 计算出当前还未拥有的销售属性
const unSelectAttrList = computed(() => {
  let unSelectArr = spuAttrList.value.filter((item) => {
    return spuHasAttrList.value.every((item1) => {
      // 当该item项都不匹配，返回true，被filter过滤除去
      return item.name !== item1.saleAttrName
    })
  })
  return unSelectArr
})

// 销售属性选择
const saleChoseAttrVal = ref('')
const addAttrFn = () => {
  console.log(saleChoseAttrVal.value)
  // 准备初始化新的对象
  const [baseSaleAttrId, saleAttrName] = saleChoseAttrVal.value.split(':')
  let newSaleAttr: spuSaleItemType = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  console.log(newSaleAttr)
  // 追加到属性表格中
  spuHasAttrList.value.push(newSaleAttr)
  saleChoseAttrVal.value = ''
}

// 点击属性值添加按钮
const handleAddAttrFn = (row: spuSaleItemType) => {
  row.flag = true
  row.saleAttrValue = ''
}

// 输入框失焦事件
const handleBlurFn = (row: spuSaleItemType) => {
  const { saleAttrValue, baseSaleAttrId } = row
  // 如果为空，返回
  if(!saleAttrValue?.trim()) {
    ElMessage.warning('属性值不能为空')
    return
  }

  // 判断属性值是否在数组中存在
  const obj = row.spuSaleAttrValueList.find(item => item.saleAttrValueName === saleAttrValue)
  if(obj) {
    ElMessage.warning('已存在相同的属性值，请更换')
    return
  }

  let newSaleAttrValue: spuSaleAttrValueListType = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue!
  }

  // 往数组内新增数据
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag = false
  row.saleAttrValue = ''
}
const vFocus = {
  mounted(el: any) {
    el.children[0].children[0].focus()
  },
}

// 点击保存按钮保存数据
const saveAttrInfoFn = async () => {
  // 收集照片墙
  spuData.value.spuImageList = spuImageList.value.map(item => ({...item, imgName: item.imgName || item.name, imgUrl: item.imgUrl || item.url}))

  // 收集销售属性
  spuData.value.spuSaleAttrList = spuHasAttrList.value

  let res;
  if(spuData.value.id) {
    // 编辑操作
    res = await saveSpuAPI(spuData.value)
  } else {
    // 新增操作
    res = await addSpuAPI(spuData.value)
  }
  if(res.code === 200) {
    ElMessage.success(res.message)
    emit('update:screen', false)
    emit('getDataFn')
  } else {
    ElMessage.error(res.message)
  }
}

defineExpose({
  initAttrDataFn,
  spuData,
  spuImageList,
  spuHasAttrList,
  typeIsInfo
})
</script>

<template>
  <el-form :model="spuData" label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        v-model="spuData.spuName"
        :disabled="typeIsInfo"
        placeholder="请输入spu名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="spuData.tmId" :disabled="typeIsInfo">
        <el-option
          v-for="item in spuTrademarkList"
          :key="item.id"
          :value="item.id"
          :label="item.tmName"
        >
          {{ item.tmName }}
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="description" label="SPU描述">
      <el-input
        v-model="spuData.description"
        type="textarea"
        :disabled="typeIsInfo"
        placeholder="请输入spu描述"
      ></el-input>
    </el-form-item>
    <el-form-item v-if="spuImageList" label="SPU照片">
      <el-upload
        v-model:file-list="spuImageList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :disabled="typeIsInfo"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        v-model="saleChoseAttrVal"
        :placeholder="`还有${unSelectAttrList.length}个未选择`"
        :disabled="typeIsInfo"
      >
        <el-option
          v-for="item in unSelectAttrList"
          :key="item.id"
          :value="`${item.id}:${item.name}`"
          :label="item.name"
        >
          {{ item.name }}
        </el-option>
      </el-select>
      <el-button
        :disabled="!saleChoseAttrVal && typeIsInfo"
        type="primary"
        icon="Plus"
        style="margin-left: 15px"
        @click="addAttrFn"
      >
        添加销售属性
      </el-button>

      <el-table :data="spuHasAttrList" border style="margin-top: 20px">
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="saleAttrName"
          label="销售属性名字"
          width="150px"
        ></el-table-column>
        <el-table-column prop="spuSaleAttrValueList" label="属性值">
          <template #default="{ row }">
            <el-tag
              v-for="(e, index) in row.spuSaleAttrValueList"
              :key="e.id"
              style="margin: 5px 10px"
              closable
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ e.saleAttrValueName }}
            </el-tag>
            <el-input
              v-model="row.saleAttrValue"
              v-focus
              v-if="row.flag"
              size="small"
              :disabled="typeIsInfo"
              style="width: 100px"
              placeholder="请输入属性值"
              @blur="handleBlurFn(row)"
              @keyup.enter="handleBlurFn(row)"
            />
            <el-button
              v-else
              size="small"
              type="primary"
              icon="Plus"
              :disabled="typeIsInfo"
              @click="handleAddAttrFn(row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template #default="{ $index }">
            <el-button
              type="danger"
              icon="Delete"
              title="删除"
              :disabled="typeIsInfo"
              @click="spuHasAttrList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button :disabled="typeIsInfo" @click="saveAttrInfoFn" type="primary">保存</el-button>
      <el-button @click="handleCancelFn">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped></style>
